﻿using System;
using System.Threading.Tasks;
using Windows.UI.Notifications;
using Windows.UI.StartScreen;
using Sumc.Client.ModernUI.Common;
using Windows.Data.Xml.Dom;

namespace Sumc.Client.ModernUI.Helpers
{
    public class SecondaryTileService : ISecondaryTileService
    {
        private readonly Uri squareLogoUri = new Uri(Constants.SquareLogoUrl);
        private readonly Uri wideLogoUri = new Uri(Constants.WideLogoUrl);

        public bool SecondaryTileExists(string tileId)
        {
            return SecondaryTile.Exists(tileId);
        }

        public async Task<bool> PinSquareSecondaryTile(string tileId, string shortName, string displayName, string arguments)
        {
            if (!this.SecondaryTileExists(tileId))
            {
                var secondaryTile = new SecondaryTile(tileId, shortName, displayName, arguments, TileOptions.ShowNameOnLogo, this.squareLogoUri, null);
                bool isPinned = await secondaryTile.RequestCreateAsync();

                return isPinned;
            }

            return true;
        }

        public async Task<bool> PinWideSecondaryTile(string tileId, string shortName, string displayName, string arguments)
        {
            if (!this.SecondaryTileExists(tileId))
            {
                var secondaryTile = new SecondaryTile(tileId, shortName, displayName, arguments, TileOptions.ShowNameOnLogo, this.squareLogoUri, this.wideLogoUri);
                bool isPinned = await secondaryTile.RequestCreateAsync();

                return isPinned;
            }

            return true;
        }

        public async Task<bool> UnpinTile(string tileId)
        {
            if (this.SecondaryTileExists(tileId))
            {
                var secondaryTile = new SecondaryTile(tileId);
                bool isUnpinned = await secondaryTile.RequestDeleteAsync();
                return isUnpinned;
            }

            return true;
        }

        public void ActivateTileNotifications(string tileId, Uri tileContentUri, PeriodicUpdateRecurrence recurrence)
        {
            var tileUpdater = TileUpdateManager.CreateTileUpdaterForSecondaryTile(tileId);
            tileUpdater.StartPeriodicUpdate(tileContentUri, recurrence);
        }

        public async void Update(string tileId, Uri tileContentUri)
        {
            var tileUpdater = TileUpdateManager.CreateTileUpdaterForSecondaryTile(tileId);
            var xmlDocument = await XmlDocument.LoadFromUriAsync(tileContentUri);
            var tileNotification = new TileNotification(xmlDocument);
            tileUpdater.Update(tileNotification);
        }
    }
}